import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import {
  createRbacRoleApi,
  updateRbacRoleApi,
  delRbacRoleApi,
  getRbacRoleShowApi,
  getRbacRoleListApi,
  getRbacMenuListTreeApi
} from "@/api/userApi";
export function useCorps() {
  const form = reactive({
    page: 1,
    perPage: 10,
    keyword: "",
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const getStatusType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "未审核" : "danger";
      case 1:
        return text ? "启用" : "primary";
      case 2:
        return text ? "禁用" : "info";
    }
  };
  const columns: TableColumnList = [
	{
	  label: "ID",
	  prop: "roleId"
	},
    {
      label: "角色名称",
      prop: "name"
    },
    {
      label: "备注",
      prop: "remarks"
    },
	{
	  label: "创建时间",
	  prop: "updatedAt"
	},
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 130
    }
  ];
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getRbacRoleListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getRbacRoleListApi(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });
    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getRbacRoleListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
	const menu = await getRbacMenuListTreeApi();
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
		menuIdsOptions: menu.result,
		parentArr: []
      };
    } else {
      const detailData = await getRbacRoleShowApi({ roleId: row.roleId });
	  if(detailData.code === 200) {
		  formInline.value = {
		    title: "修改",
		  	menuIdsOptions: menu.result,
		    roleId: row?.roleId ?? "",
		    name: detailData?.result?.name ?? "",
		    remarks: detailData?.result?.remarks ?? "",
		    menuIds: detailData?.result?.menuIds ?? [],
		  	// dataPermission: detailData?.result?.dataPermission ?? "",
		  	parentArr: detailData?.result?.menuIds ?? []
		  };
	  } else {
		message(detailData.msg ?? "操作失败,请联系管理员", {
		  type: "error"
		});
		return
	  }
      
    }
    addDialog({
      title: `${title}信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

		const params = {
			roleId: curData.roleId,
			name: curData.name,
			remarks: curData.remarks,
			menuIds: curData.parentArr,
			dataPermission: curData.dataPermission
		}
		
        function chores() {
          message(`${title}成功`, {
            type: "success"
          });
          done();
          onSearch();
        }
        FormRef.validate(valid => {
          if (valid) {
			if(params.menuIds.length === 0){
				message("角色菜单不能为空！", {
				  type: "error"
				});
				return
			}
            if (title === "新增") {
              createRbacRoleApi(params)
                .then((res) => {
					if(res.code === 200) {
						chores();
					} else {
						message(res.msg ?? "操作失败,请联系管理员", {
						  type: "error"
						});
					}
                  
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateRbacRoleApi(params)
                .then((res) => {
				  if(res.code === 200) {
				  	chores();
				  } else {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  }
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
	
  });

  function handleDelete(row) {
    delRbacRoleApi({ roleId: row.roleId }).then((res) => {
		if(res.code === 200) {
			message(`删除成功`, { type: "success" });
			onSearch();
		} else {
			message(res.msg ?? "操作失败,请联系管理员", {
			  type: "error"
			});
		}
      
    });
  }
  function confirmStatus() {
    alert("审核通过");
  }
  function refusedStatus() {
    alert("审核拒绝");
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete,
    confirmStatus,
    refusedStatus
  };
}
